package cn.openea.perpartner.timeline.interceptor;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Weird077
 * @description TODO
 * @date 2022-12-01 19:06
 */
@Slf4j
@Component
public class TimelinePermissionInterceptor implements HandlerInterceptor {
    @Value("${timeline.header.sysid}")
    private String sysId;
    @Value("${timeline.header.syspwd}")
    private String sysPwd;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        if (StrUtil.isBlank(request.getHeader("sysid")) || StrUtil.isBlank(request.getHeader("syspwd"))) {
            response.getWriter().println("{\"code\":\"201\", \"msg\":\"sysid or syspwd are not allowed to be empty!\"}");
            return false;
        }
        String valid = request.getHeader("sysid").concat(request.getHeader("syspwd"));
        if (!valid.equals(sysId.concat(sysPwd))) {
            response.getWriter().println("{\"code\":\"201\", \"msg\":\"sysid and syspwd validate failed!\"}");
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) throws Exception {
    }
}
